package TTEST;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import Files.File_;


public class InternalFrameDemo extends javax.swing.JFrame implements ActionListener {
	static List<LabWindow> allconnections=new ArrayList<LabWindow>();
	public static List<LabWindow> getAllConnections(){
		return allconnections;
	}
	JDesktopPane desktop;
	private WindowAdapter windowAdapter;
	private ReadCommandsThread rct;
    public InternalFrameDemo() {
        super("CLI > GUI Interface Test Tool");
        if(new File_().isbasedirectory())
        {
        	System.out.println("ok");
        }
        rct=  new ReadCommandsThread();rct.start();
  		  windowAdapter = new WindowAdapter()
  	        {
  	            public void windowClosing(WindowEvent we)
  	            {
  	            	for (LabWindow lab: allconnections) {
  	            		
						while(lab.ct.isAlive())
						{
							lab.ct.td.rc.interrupt();
							System.out.println("Thread which was responsible for reading output stream has been stopped");
							try{ Thread.sleep(500);}catch(Exception e ) {};
	  	            		System.out.println("Waiting for stop connection with "+lab.host);
	  	            		lab.ct.interrupt();
						}
						System.out.println("Connection with "+lab.host+" has been closed");
					}
  	            	rct.setEndWork();
  	            	while(rct.isAlive())
  	            	{
  	            		try{ Thread.sleep(1000);}catch(Exception e ) {};
  	            		System.out.println("Waiting for stop all threads");
  	            	}
  	            	System.out.println("End work of CLI application");
  	                //setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
  	                System.exit(0);
  	            }
  	        };

  	        addWindowListener(windowAdapter);
        //Make the big window be indented 50 pixels from each edge
        //of the screen.
        int inset = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(inset, inset,
                  screenSize.width  - inset*2,
                  screenSize.height - inset*2);
 
        //Set up the GUI.
        desktop = new JDesktopPane(); //a specialized layered pane
      //  createFrame(); //create first "window"
        setContentPane(desktop);
        setJMenuBar(createMenuBar());
 
        //Make dragging a little faster but perhaps uglier.
        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    }
    void AddToMenu(JMenu value){
    	menuBar.add(value);
    }
    
    JMenuBar menuBar = new JMenuBar();
    protected JMenuBar createMenuBar() {
    	//File_.htmlparse aa =new File_().new htmlparse();
    	//new File("c:dateFormat.format(cal.getTime())").mkdir();
        //Set up the lone menu.
    	File_.onlyReadFile(0);File_.onlyReadFile(1);
        JMenu menu = new JMenu("Labs");
        menu.setMnemonic(KeyEvent.VK_D);
        AddToMenu(menu);
        JMenu menu2 = new JMenu("Commands");
        menu.setMnemonic(KeyEvent.VK_D);
        AddToMenu(menu2);
 
        //Set up the first menu item.
        JMenuItem menuItem = new JMenuItem("Commands");
        menuItem.setMnemonic(KeyEvent.VK_N);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_N, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("commands");
        menuItem.addActionListener(this);
        menu.add(menuItem);
        
        ///////////////
        if(new File_().openFile(1)){
        File_.common_map_labs= new File_().readF(1);
		if (!File_.common_map_labs.isEmpty()){
			for (Entry<String,String> t : File_.common_map_labs.entrySet()) {
				JMenuItem temp=new JMenuItem(t.getKey());
				temp.setName(t.getKey());
				StringTokenizer st2=new StringTokenizer(t.getValue()," " );
				while (st2.hasMoreElements()) {
					System.out.println(st2.nextElement());
				}
				temp.setActionCommand("definedlabs");
				temp.addActionListener(this);
	        	menu.add(temp);
			}
		} 
        }
        JMenuItem menulabs = new JMenuItem("Labs");
        menulabs.setActionCommand("labs");
        menulabs.addActionListener(this);
        	menu.add(menulabs);
        //////////////
 
        //Set up the second menu item.
        menuItem = new JMenuItem("Quit");
        menuItem.setMnemonic(KeyEvent.VK_Q);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_Q, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("quit");
        menuItem.addActionListener(this);
        menu.add(menuItem);
 
        return menuBar;
    }
    static String _lab;
    //React to menu selections.
    public void actionPerformed(ActionEvent e) {
    	if ("labs".equals(e.getActionCommand()))  {
    		crealeLab(((JMenuItem )e.getSource()).getName());}
        if ("commands".equals(e.getActionCommand())) {
        	crealeCommands();
        }
        if("definedlabs".equals(e.getActionCommand())) { 
    		createFrame(((JMenuItem )e.getSource()).getName());
        }
    }
    protected void crealeLab(String name){
    	Commands_Labs_ frame=new Commands_Labs_(0/*,"Labs"*/);
    	frame.setVisible(true); 
        desktop.add(frame);
    }
     void crealeCommands(){
    	 Commands_Labs_ frame=new Commands_Labs_(1/*,"Commands"*/);
     	frame.setVisible(true); 
         desktop.add(frame);
    }
 
    //Create a new internal frame.
    protected void createFrame(String temp) {
    	/*SwingShell ss=new SwingShell();
    	desktop.add(ss);*/
    	//MyInternalFrame frame=new MyInternalFrame();
    	//LabWindow[] lista = new LabWindow[2];
    	//10.91.57.158
    	//lista.
    	LabWindow frame=new LabWindow(temp);
    	allconnections.add(frame);
    	//SwingShell frame = new SwingShell();
        frame.setVisible(true); 
        desktop.add(frame);
        
    //	LabWindow frame1=new LabWindow();
    	//SwingShell frame = new SwingShell();
     //   frame1.setVisible(true); 
    //    desktop.add(frame1);
        /*try {
            frame.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {}*/
    }
 
    //Quit the application.
    protected void quit() {
        System.exit(0);
    }
 
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
 
        //Create and set up the window.
        InternalFrameDemo frame = new InternalFrameDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Display the window.
        frame.setVisible(true);
    }
 
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}
